﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Messaging;
using JiveMessenger.Log;
using JiveMessenger.User;
using JiveMessenger.Utilities;
using JmShared;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Linq;
using Windows.Storage;
using Windows.UI.Xaml.Media.Imaging;
using GalaSoft.MvvmLight.Views;
using Windows.Storage.Pickers;
using Windows.ApplicationModel.Activation;

namespace JiveMessenger.ViewModels
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class ViewModelAddEmoticon : ViewModelBaseEx
#if WINDOWS_PHONE_APP
, IFileOpenPickerContinuable
#endif
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
        private const int MaxEmoticonHeigth = 70;
        private const int MaxEmoticonWidth = 200;
        private IClient _currentClient;
        private INavigationService _navigationService;
        private bool _tooBigPixelSize;
        public RelayCommand BrowseForImageCommand { get; private set; }
        public RelayCommand SaveEmoticonCommand { get; private set; }
        public string OriginalShortCut;
        public bool IsEmoticonSaved { get; set; }

        private StorageFile _emoticonFile;
        public StorageFile EmoticonFile
        {
            get { return _emoticonFile; }
            set
            {
                if (_emoticonFile != value)
                {
                    _emoticonFile = value;
                    RaisePropertyChanged("EmoticonFile");
                    RaisePropertyChanged("IsShortcutTextBoxEnabled");
                }
            }
        }

        private string _imageErrorText;
        public string ImageErrorText
        {
            get { return _imageErrorText; }
            set
            {
                if (_imageErrorText != value)
                {
                    _imageErrorText = value;
                    RaisePropertyChanged("ImageErrorText");
                }
            }
        }

        private string _emoticonShortcut;
        public string EmoticonShortcut
        {
            get { return _emoticonShortcut; }
            set
            {
                if (_emoticonShortcut != value)
                {
                    _emoticonShortcut = value;
                    RaisePropertyChanged("EmoticonShortcut");
                }
            }
        }

        public bool IsShortcutTextBoxEnabled
        {
            get
            {
                return EmoticonFile != null;
            }
        }
        private string _shortcutErrorText;
        public string ShortcutErrorText
        {
            get { return _shortcutErrorText; }
            set
            {
                if (_shortcutErrorText != value)
                {
                    _shortcutErrorText = value;
                    RaisePropertyChanged("ShortcutErrorText");
                }
            }
        }


        private bool _isOkButtonEnabled;
        public bool IsOkButtonEnabled
        {
            get { return _isOkButtonEnabled; }
            set
            {
                if (_isOkButtonEnabled != value)
                {
                    _isOkButtonEnabled = value;
                    RaisePropertyChanged("IsOkButtonEnabled");
                    SaveEmoticonCommand.RaiseCanExecuteChanged();
                }
            }
        }

        private BitmapSource _emoticonImageSource;
        public BitmapSource EmoticonImageSource
        {
            get { return _emoticonImageSource; }
            set
            {
                if (_emoticonImageSource != value)
                {
                    _emoticonImageSource = value;
                    RaisePropertyChanged("EmoticonImageSource");
                }
            }
        }
        ~ViewModelAddEmoticon()
        {
            Logger.Debug("ViewModelAddEmoticon destructed");
        }

        /// <summary>
        /// Initializes a new instance of the ViewModelAddEmoticon class.
        /// </summary>
        public ViewModelAddEmoticon(IClient currentClient, INavigationService navService)
        {
            _currentClient = currentClient;
            _navigationService = navService;
            BrowseForImageCommand = new RelayCommand(BrowseForImageCommandAction);
            PropertyChanged += ViewModelAddEmoticon_PropertyChanged;
            SaveEmoticonCommand = new RelayCommand(SaveEmoticonCommandAction, () => IsOkButtonEnabled);
        }

        private async void SaveEmoticonCommandAction()
        {
            HashSet<ContactEmoticon> emoticons = _currentClient.UserSettings.CustomEmoticons;
            string hash = await StaticMethods.ComputeMD5Async(await StaticMethods.LoadImageData(EmoticonFile));
            if (!emoticons.Any(x => x.Keyword == EmoticonShortcut))
            {
                emoticons.Add(new ContactEmoticon()
                {
                    Keyword = EmoticonShortcut,
                    Hash = hash,
                    Index = emoticons.Select(x => x.Index).OrderBy(n => n).LastOrDefault() + 1,
                    Extension = Path.GetExtension(EmoticonFile.Path)
                });
            }
            _currentClient.UserSettings.CustomEmoticons = _currentClient.CurrentUserInfo.CustomEmoticons = emoticons;
            Messenger.Default.Send(new NotificationMessage(this, "UpdateCustomEmoticons"));
            WpUserSettings settings = new WpUserSettings();
            settings.CustomEmoticons = _currentClient.UserSettings.CustomEmoticons;
            if (await _currentClient.Connection.SendCommand(settings, ClientCommands.WpSettings))
                IsEmoticonSaved = true;
            _navigationService.GoBack();
        }

        public override void Cleanup()
        {

            SimpleIoc.Default.Unregister<ViewModelAddEmoticon>(VmHelper.Locator.ViewModelAddEmoticonKey);
            VmHelper.Locator.ViewModelAddEmoticonKey = System.Guid.NewGuid().ToString();
            PropertyChanged -= ViewModelAddEmoticon_PropertyChanged;
            base.Cleanup();
        }

        void ViewModelAddEmoticon_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "EmoticonShortcut":
                    ValidateShortcut();
                    break;
            }
        }

        private void ValidateShortcut()
        {
            string error;
            if (!this._currentClient.ValidateEmoticonShortcut(this.EmoticonShortcut, this.OriginalShortCut, out error))
            {
                this.ShortcutErrorText = error;
                this.IsOkButtonEnabled = false;
            }
            else if (!String.IsNullOrEmpty(this.EmoticonShortcut) && !this._tooBigPixelSize)
            {
                this.ShortcutErrorText = "";
                this.IsOkButtonEnabled = true;
            }
            else
                this.IsOkButtonEnabled = false;
        }

        private async void BrowseForImageCommandAction()
        {
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");
            openPicker.FileTypeFilter.Add(".bmp");
#if WINDOWS_PHONE_APP
            // Launch file open picker and caller app is suspended and may be terminated if required
            openPicker.PickSingleFileAndContinue();
#else
          StorageFile file  = await  openPicker.PickSingleFileAsync();
          _navigationService.NavigateTo("CropImagePage", new Tuple<ImageCropType, StorageFile>(ImageCropType.Emoticon, file));
#endif

        }

#if WINDOWS_PHONE_APP
        /// <summary>
        /// Handle the returned files from file picker
        /// This method is triggered by ContinuationManager based on ActivationKind
        /// </summary>
        /// <param name="args">File open picker continuation activation argment. It cantains the list of files user selected with file open picker </param>
        public void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
        {
            if (args.Files.Count > 0)
            {
                Debug.WriteLine("Picked photo: " + args.Files[0].Name);
                _navigationService.NavigateTo("CropImagePage", new Tuple<ImageCropType, StorageFile>(ImageCropType.Emoticon, args.Files[0]));
                //ProcessEmoticonImage(args.Files[0]);
            }
            else
            {
                Debug.WriteLine("Operation cancelled.");
            }

        }
#endif
        public async Task ProcessEmoticonImage(StorageFile file)
        {
            if (file == null)
                return;
            EmoticonFile = file;
            BitmapImage image = await StaticMethods.LoadBitmapImageFromIsolatedStorage(file);
            bool isGif = EmoticonFile.FileType == ".gif";
            int sizeInKB = isGif ? 150 : 50;
            var properties = await file.GetBasicPropertiesAsync();
            bool tooBigFileSize = properties.Size > 1024.0 * sizeInKB;
            _tooBigPixelSize = false;//CheckImageSize(image);

            if (tooBigFileSize)
            {

                ImageErrorText = string.Format("Max file size is {0}", "50KB", "150KB (gif)");
                IsOkButtonEnabled = false;
                EmoticonFile = null;
            }
            else if (_tooBigPixelSize)
            {

                ImageErrorText = string.Format("Image is larger than {0}x{1} px.", MaxEmoticonWidth, MaxEmoticonHeigth);
                IsOkButtonEnabled = false;
                EmoticonFile = null;
            }
            else
            {
                if (!string.IsNullOrEmpty(EmoticonShortcut))
                    IsOkButtonEnabled = true;
                ImageErrorText = "";
            }
            if (EmoticonFile != null)
                SetImage(image);
            Messenger.Default.Send(new NotificationMessage(this, "FocusShortcutTextbox"));
        }
        private void SetImage(BitmapImage source)
        {
            this.EmoticonImageSource = source; //StaticMethods.BitmapFromUri(new Uri(source));
        }
        //private bool CheckImageSize(BitmapImage imageSource)
        //{
        //    bool tooBig=false;
        //  //  BitmapSource imageSource = StaticMethods.ByteArrayToBitmap(imageBytes);



        //    if (imageSource.PixelWidth > MaxEmoticonWidth)
        //    {
        //        tooBig = true;
        //    }

        //    if (imageSource.PixelHeight > MaxEmoticonHeigth)
        //    {
        //        tooBig = true;
        //    }
        //    return tooBig;
        //}
    }
}